package com.kaifamiao.mybatis.anno.mapper;

import com.kaifamiao.mybatis.anno.entity.Customer;
import com.kaifamiao.mybatis.anno.type.BooleanTypeHandler;
import com.kaifamiao.mybatis.anno.type.LocalDateTypeHandler;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface CustomerMapper {

    @Select("SELECT id, email, tel, password, birthdate, married FROM t_customers WHERE id = #{id}")
    @Results(
       value = {
       @Result( column = "id", property = "id", id = true ) ,
       @Result( column = "email", property = "email") ,
       @Result( column = "tel", property = "tel") ,
       @Result( column = "password", property = "password"),
       @Result( column = "birthdate", typeHandler = LocalDateTypeHandler.class, property = "birthdate"),
       @Result( column = "married", typeHandler = BooleanTypeHandler.class, property = "married")
       },
       id = "customerResultMap"
    )
    Customer find(Integer id);

    @Select("SELECT id, email, tel, password, birthdate, married FROM t_customers ORDER BY id")
    @ResultMap("customerResultMap")
    List<Customer> findAll();

    @Insert("INSERT INTO t_customers " +
                "(id, email, tel, password, birthdate, married)" +
            " VALUES " +
                "(#{id}, #{email}, #{tel}, #{password}, #{birthdate, typeHandler=LocalDateTypeHandler}, #{married, typeHandler=BooleanTypeHandler})")
    @SelectKey(keyProperty = "id",
               resultType = Integer.class,
               statement = "SELECT NVL(MAX(id), 0) + 1 FROM t_customers",
               before = true,
               databaseId = "oracle")
    int persist( Customer c );

    @Update( "UPDATE t_customers " +
             "SET " +
             "email = #{email}, " +
             "tel= #{tel}, " +
             "password = #{password}, " +
             "birthdate = #{birthdate, typeHandler=LocalDateTypeHandler}, " +
             "married = #{married, typeHandler=BooleanTypeHandler} " +
             "WHERE id = #{id}")
    int update( Customer c );

    @Delete("DELETE FROM t_customers WHERE id = #{id}")
    int remove( Integer id );

}
